<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>$Title$</title>
    <script type="text/javascript" src="https://code.jquery.com/jquery-3.7.1.js"></script>
</head>
<body>
<form action="" method="post">
    <label>手机号码:</label>
    <input type="text" name="phone"/>
    <br/>
    <input type="text" name="valCode"/>
    <button type="button" id="btn">获取验证码</button>
    <br/>
    <input type="submit" id="subBtn" value="登录"/>
</form>
<script type="text/javascript">
    $(function () {
        //灰掉  禁用
        $("#subBtn").attr("disabled", "disabled");

        $("#btn").click(function () {
            let phone = $("input[name=phone]").val();
            let reg = /^1[3456789][0-9]{9}$/
            if (!reg.test(phone)) {
                alert("请填写正确的手机号码");
            } else {
                //发送异步请求
                sendSms(phone);
                //倒计时
            }
        });

        $("input[name=valCode]").blur(function () {
            let valCode = $(this).val();
            let reg = /^\d{4}$/
            if (!reg.test(valCode)) {
                alert("请输入正确的验证码格式，4位纯数字");
            } else {
                valSmsCode(valCode);
            }
        });
    })
    let myTimer;

    function sendSms(phone) {
        $.ajax({
            url: "/sendSms",
            type: "post",
            data: {
                phone: phone
            },
            dataType: "json",
            success(data) {
                if (data.code === "0000") {
                    $("#btn").attr("disabled", "disabled")
                    $("#btn").text("倒计时(60s)")
                    myTimer = setInterval(function () {
                        djs();
                    }, 1000);
                }
            }
        })
    }

    let time = 60;

    function djs() {
        time--;
        $("#btn").text("倒计时(" + time + "s)");
        if (time == 0) {
            $("#btn").removeAttr("disabled");
            $("#btn").text("获取验证码");
            clearInterval(myTimer);
        }
    }

    function valSmsCode(valCode) {
        let phone = $("input[name=phone]").val();
        $.post("/valSmsCode", {phone: phone, valCode: valCode}, function (data) {
            if (data.code === "0000") {
                $("#subBtn").removeAttr("disabled")
            } else {
                $("#subBtn").attr("disabled", "disabled")
            }
        }, "json");
    }
</script>
</body>
</html>
